﻿Imports Microsoft.Win32
Imports Global_Visas_Business_Layer
Imports System.ComponentModel
Imports System.IO
Imports System.Windows.Forms
Imports System.Text
Imports System.Net.Mail

Partial Public Class frmSendEmail
    Public blnEmailToPerson As Boolean
    Public iEmailType As Integer
    Public emailEvent As Long

    Private Sub btnAddAttach_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddAttach.Click
        Dim i As Integer
        Dim OpenFileDialog1 As New System.Windows.Forms.OpenFileDialog
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            For i = 0 To OpenFileDialog1.FileNames.Length - 1
                Me.lstAttach.Items.Add(IO.Path.GetFileName(OpenFileDialog1.FileNames(i).ToString))
                GlobalCRM.LocalAttachments.AddAttachment(IO.Path.GetFileName(OpenFileDialog1.FileNames(i).ToString), OpenFileDialog1.FileNames(i).ToString)
            Next
        End If
    End Sub

    Private Sub btnTo_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnTo.Click
        Dim frmAddressBook As New frmAddressBook
        Try
            frmAddressBook.ShowDialog()
            Me.txtTo.Text = Me.txtTo.Text & ";" & frmAddressBook.SelectedAddresses
            frmAddressBook.Close()
        Catch ex As Exception
            Dim incidentno As Long
            incidentno = CommonFuncs.ErrorHandler(ex, "Frmsendemail : btnTo_Click")
            If incidentno > 0 Then
                CommonFuncs.DisplayMessage("The incident has been created and sent to IT." & vbCrLf & vbCrLf & "Please quote the incident number : " & incidentno & " to It for future correspondences", CommonDialog.CustomDialogIcons.Information, "IT")
            Else
                CommonFuncs.DisplayMessage("Please contact IT directly. The message was not created.", CommonDialog.CustomDialogIcons.Information, "IT")
            End If
        Finally
            frmAddressBook = Nothing
        End Try
    End Sub

    Private Sub frmSendEmail_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Try
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)
            Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
            Dim creg As New CReg
            Dim tmrEmail As New Timers.Timer
            Dim value As String
            Dim caseid As String = creg.ReadValue(GlobalCRM.GLOBALVISA, GlobalCRM.CUST, GlobalCRM.Reg_CurrentCASEID, value)
            Dim strRegValue As String = creg.ReadValue(GlobalCRM.GLOBALVISA, GlobalCRM.CUST, GlobalCRM.DRAFTSAVELOC, value)
            If strRegValue Is Nothing Then
                strRegValue = CommonDataFunctions.getDraftForConsultant(GlobalCRM.CurrentConID)
            End If
            Dim fFile As New IO.FileInfo(strRegValue & "\" & GlobalCRM.CurrentNTUserName & GlobalCRM.DraftFile & caseid & ".rtf")
            Dim txtrange As TextRange
            If fFile.Exists Then

                txtrange = New TextRange(txtbody.Document.ContentStart, txtbody.Document.ContentEnd)
                Dim fStream As FileStream
                fStream = New FileStream(strRegValue & "\" & GlobalCRM.CurrentNTUserName & GlobalCRM.DraftFile & caseid & ".rtf", FileMode.OpenOrCreate)
                txtrange.Load(fStream, System.Windows.DataFormats.Text)

                fStream.Close()
            Else
            End If

            tmrEmail.Enabled = True
            RemoveHandler drpTemplates.SelectionChanged, AddressOf drpTemplates_SelectedIndexChanged
            'frmMDIMain.SaveEmailToolStripMenuItem.Enabled = True
            Me.lstAttach.Items.Clear()
            If GlobalCRM.LocalAttachments.Attachments.Count > 0 Then
                Dim myAttach As GlobalCRM.LocalAttachments.LocalAttachment

                For Each myAttach In GlobalCRM.LocalAttachments.Attachments
                    Me.lstAttach.Items.Add(CType(myAttach, GlobalCRM.LocalAttachments.LocalAttachment).Name)
                Next
            End If

            With Me.drpTemplates
                .DisplayMemberPath = "EMailTemplate_Name"
                .SelectedValuePath = "EMailTemplate_ID"
                .ItemsSource = CType(CommonDataFunctions.GetEmailTemplateList(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentCompanyID), IListSource).GetList()
                .SelectedIndex = -1
            End With

            Me.txtSignature.Text = CommonDataFunctions.GblFunc_Get_Sigfile(GlobalCRM.CurrentConID)
            'Select Case iEmailType
            '    Case CommonDataFunctions.EmailType.Blank
            '        Me.txtTo.Text = String.Empty
            '    Case CommonDataFunctions.EmailType.Both
            Dim strContactEmailAddr As String
            strContactEmailAddr = People.GetEmailAddress(GlobalCRM.CurrentContactID)
            If strContactEmailAddr = String.Empty Then
                Me.txtTo.Text = People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID)
            Else
                Me.txtTo.Text = strContactEmailAddr
                'Me.txtTo.Text = strContactEmailAddr & ";" & People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID)
            End If

            '    Case CommonDataFunctions.EmailType.Candidate
            'Me.txtTo.Text = People.GetCandidateEmailAddress(GlobalCRM.CurrentCaseID)
            '    Case CommonDataFunctions.EmailType.Contact
            'Me.txtTo.Text = People.GetEmailAddress(GlobalCRM.CurrentContactID)
            'End Select

            AddHandler drpTemplates.SelectionChanged, AddressOf drpTemplates_SelectedIndexChanged
        Catch ex As Exception
            Dim incidentno As Long
            incidentno = CommonFuncs.ErrorHandler(ex, "frmSendEmail : frmSendEmail_Loaded")
            If incidentno > 0 Then
                CommonFuncs.DisplayMessage("The incident has been created and sent to IT." & vbCrLf & vbCrLf & "Please quote the incident number : " & incidentno & " to It for future correspondences", CommonDialog.CustomDialogIcons.Information, "IT")
            Else
                CommonFuncs.DisplayMessage("Please contact IT directly. The message was not created.", CommonDialog.CustomDialogIcons.Information, "IT")
            End If
        End Try
    End Sub
    Private Sub drpTemplates_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpTemplates.SelectionChanged

        Dim myTemplate As Letters.EmailTemplate
        Try

            Dim textRange As TextRange = New TextRange(txtbody.Document.ContentStart, txtbody.Document.ContentEnd)

            If textRange.Text <> "" Then
                If MsgBox("Existing message will be lost, are you sure?", vbYesNo + vbExclamation, "Apply Template") <> MsgBoxResult.Yes Then
                    Exit Sub
                End If
            End If

            myTemplate = Letters.GetEmailTemplate(Me.drpTemplates.SelectedValue)

            Me.txtSubject.Text = Letters.Gblfunc_Process_Bookmarks(myTemplate.Subject, GlobalCRM.CurrentCaseID, 1)


            If Strings.Left(textRange.Text, 1) = ">" Then
                textRange.Text = Letters.Gblfunc_Process_Bookmarks(myTemplate.Body, GlobalCRM.CurrentCaseID, 1) & vbCrLf & vbCrLf & textRange.Text
            Else
                textRange.Text = Letters.Gblfunc_Process_Bookmarks(myTemplate.Body, GlobalCRM.CurrentCaseID, 1)
            End If

        Catch ex As Exception
            Dim incidentno As Long
            incidentno = CommonFuncs.ErrorHandler(ex, "frmSendEmail : drpTemplates_SelectedIndexChanged")
            If incidentno > 0 Then
                CommonFuncs.DisplayMessage("The incident has been created and sent to IT." & vbCrLf & vbCrLf & "Please quote the incident number : " & incidentno & " to It for future correspondences", CommonDialog.CustomDialogIcons.Information, "IT")
            Else
                CommonFuncs.DisplayMessage("Please contact IT directly. The message was not created.", CommonDialog.CustomDialogIcons.Information, "IT")
            End If
        End Try
    End Sub

    Private Sub btnbcc_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnbcc.Click
        Dim frmAddressBook As New frmAddressBook
        frmAddressBook.ShowDialog()
        Me.txtCC.Text = frmAddressBook.SelectedAddresses
        frmAddressBook.Close()
        frmAddressBook = Nothing
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click
        Dim frmAddressBook As New frmAddressBook
        frmAddressBook.ShowDialog()
        Me.txtBCC.Text = frmAddressBook.SelectedAddresses
        frmAddressBook.Close()
        frmAddressBook = Nothing
    End Sub
    Private Function validateUI() As Boolean
        Dim txtbodyData As TextRange = New TextRange(txtbody.Document.ContentStart, txtbody.Document.ContentEnd)
        If Me.txtTo.Text.Trim = String.Empty Then
            CommonFuncs.DisplayMessage("Cannot have a blank To: line.", CommonDialog.CustomDialogIcons.Information, "Error")
            Return False
        End If

        If Me.txtSubject.Text.Trim = String.Empty Then
            CommonFuncs.DisplayMessage("Cannot have a blank subject line.", CommonDialog.CustomDialogIcons.Information, "Error")
            Return False
        End If

        If txtbodyData.Text.Trim = String.Empty Then
            CommonFuncs.DisplayMessage("Cannot have a blank body.", CommonDialog.CustomDialogIcons.Information, "Error")
            Return False
        End If

        If txtTo.Text <> String.Empty Then
            If CommonFuncs.isEmailValid(txtTo.Text) = False Then
                CommonFuncs.DisplayMessage("Please enter a valid TO Email address", CommonDialog.CustomDialogIcons.Information, "Invalid Email address")
                Return False
            End If
        End If
        If txtCC.Text <> "" Then
            If CommonFuncs.isEmailValid(txtCC.Text) = False Then
                CommonFuncs.DisplayMessage("Please enter a valid CC Email address", CommonDialog.CustomDialogIcons.Information, "Invalid Email address")
                Return False
            End If
        End If
        If txtBCC.Text <> "" Then
            If CommonFuncs.isEmailValid(txtBCC.Text) = False Then
                CommonFuncs.DisplayMessage("Please enter a valid BCC Email address", CommonDialog.CustomDialogIcons.Information, "Invalid Email address")
                Return False
            End If
        End If
        Return True
    End Function
    Private Sub btnSend_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSend.Click
        '        Dim intRow As Integer
        'Dim objAttach As GlobalCRM.LocalAttachments
        Dim StrDir As String
        Dim DocStoreId As Long
        Dim txtbodyData As TextRange = New TextRange(txtbody.Document.ContentStart, txtbody.Document.ContentEnd)
        Dim CReg As New CReg
        Dim tsk As New TasksEvents
        Try

          
            If validateUI() = True Then
                Dim myCon As CommonDataFunctions.ConsultantInfo = CommonDataFunctions.GetConsultantInfo(GlobalCRM.CurrentConID)

                Dim Attach As GlobalCRM.LocalAttachments.LocalAttachment

                If myCon.ConId = 0 Then
                    CommonFuncs.DisplayMessage("Cannot get senders address, unable to use mail engine. Please uncheck the mail engine box and try again", CommonDialog.CustomDialogIcons.Information, "Error")
                    Exit Sub
                End If
                If myCon.Email.Trim = String.Empty Then
                    CommonFuncs.DisplayMessage("Your e-mail address has not been entered onto the database, cannot use the mail engine.", CommonDialog.CustomDialogIcons.Information, "Error")
                    Exit Sub
                End If

                If GlobalCRM.LocalAttachments.Attachments.Count > 0 Then
                    'Add files to Docstore then pass Docstore ID to the mail engine

                    DocStoreId = Letters.GblFunc_Create_DocStore("Files E-Mailed", "Documents E-Mailed", GlobalCRM.CurrentCaseID, 1)

                    For Each Attach In GlobalCRM.LocalAttachments.Attachments
                        If Letters.GblFunc_Add_FileToStore(Attach.Filepath, Strings.Left(Attach.Name, 99), DocStoreId) = 0 Then
                            CommonFuncs.DisplayMessage("Couldn't find attachment file, send failed", CommonDialog.CustomDialogIcons.Information, "Error")
                            Exit Sub
                        End If
                    Next

                End If


                Dim fFile As IO.FileInfo
                Dim strRegValue As String
                Dim caseid As String
                Dim value As String

                If Me.chkBCCSender.IsChecked Then
                    Me.txtBCC.Text = myCon.Email & ";" & Me.txtBCC.Text
                End If

              

                Me.btnCancel.Focus()
                Me.btnSend.IsEnabled = False
                Dim Subj, Msgstr, CC, Bcc, Tostr As String

                Subj = txtSubject.Text.Trim
                Msgstr = txtbodyData.Text.Trim
                CC = txtCC.Text.Trim
                Bcc = txtBCC.Text.Trim

                Tostr = txtTo.Text.Trim

                Dim casestage As Cases.CaseStage
                Dim EmailTo As String = String.Empty
                Dim EmailFrom As String = String.Empty
                casestage = Cases.GetCaseStage(GlobalCRM.CurrentCaseID)
                Dim sqlbldr As New StringBuilder
                If EmailFrom = String.Empty Then
                    EmailFrom = CommonDataFunctions.EmailFrom()
                End If
                If EmailFrom Is Nothing Then
                    MsgBox("Your email id is not updated in the database." & vbCrLf & "Please contact IT", MsgBoxStyle.Critical, "Email Not sent")
                End If

                If GlobalCRM.CurrentCompanyID = 0 Then
                    EmailTo = People.GetemailAddressFromID(GlobalCRM.CurrentCandidateID)


                End If
                If GlobalCRM.CurrentCompanyID > 0 Then
                    Dim candid1 As Long
                    Select Case iEmailType
                        Case CommonDataFunctions.EmailType.Candidate
                            candid1 = GlobalCRM.CurrentCandidateID
                        Case CommonDataFunctions.EmailType.Contact
                            candid1 = GlobalCRM.CurrentContactID
                    End Select
                  
                    EmailTo = People.GetemailAddressFromID(candid1)
                End If
                If EmailTo Is Nothing Then
                    CommonFuncs.DisplayMessage("The Email address of the client is not found in the system. Hence email has not been sent", CommonDialog.CustomDialogIcons.Information, "Email Not sent")
                    Me.Close()
                    Exit Sub
                End If
                If casestage.StageNumber >= 100 And casestage.StageNumber < 1000 And EmailTo.Trim = txtTo.Text.Trim And txtCC.Text.Trim = String.Empty And txtBCC.Text.Trim = String.Empty Then 'And GlobalCRM.CurrentCompanyID = 0
                    If DocStoreId > 0 Then
                        StrDir = Letters.Gblfunc_Get_DocStorePath(DocStoreId)
                    End If
                    'Dim condet As CommonSQL.ConsultantInfo = CommonSQL.GetConsultantInfo(GlobalCRM.CurrentConID)
                    Dim candid As Long
                    If GlobalCRM.CurrentCompanyID = 0 Then
                        candid = GlobalCRM.CurrentCandidateID
                    ElseIf GlobalCRM.CurrentCompanyID > 0 Then
                        Select Case iEmailType
                            Case CommonDataFunctions.EmailType.Candidate
                                candid = GlobalCRM.CurrentCandidateID
                            Case CommonDataFunctions.EmailType.Contact
                                candid = GlobalCRM.CurrentContactID
                        End Select
                    End If
                    If Letters.SendMailMessage(Me.txtTo.Text.Trim, GlobalCRM.CurrentConID, GlobalCRM.CurrentCaseID, txtSubject.Text.Trim, txtbodyData.Text.Trim & vbCrLf & "Global Visas Team", candid, txtCC.Text.Trim, txtBCC.Text.Trim, StrDir) = 0 Then
                        Me.btnSend.IsEnabled = True
                        CommonFuncs.DisplayMessage("Error. Message could not be added to the S_SendEmail table.", CommonDialog.CustomDialogIcons.Information, "Error")
                        Exit Sub
                    Else
                        ' Dim msgbody As StringBuilder

                        'CommonDataFunctions.SendEmailToClient_ForLoginArea(GlobalCRM.CurrentCandidateID, iEmailType)

                        tsk.GblFunc_Add_Event("Send Email", "The email has been sent to the client and is viewable through login Area : " & vbCrLf & "Subject :" & Subj & vbCrLf & "Body :" & vbCrLf & Msgstr, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , 1)

                        GlobalCRM.LocalAttachments.Attachments.Clear()


                        caseid = CReg.ReadValue(GlobalCRM.GLOBALVISA, GlobalCRM.CUST, GlobalCRM.Reg_CurrentCASEID, value)
                        strRegValue = CReg.ReadValue(GlobalCRM.GLOBALVISA, GlobalCRM.CUST, GlobalCRM.DRAFTSAVELOC, value)
                        If strRegValue Is Nothing Then
                            strRegValue = CommonDataFunctions.getDraftForConsultant(GlobalCRM.CurrentConID)
                        End If
                        fFile = New IO.FileInfo(strRegValue & "\" & GlobalCRM.CurrentNTUserName & GlobalCRM.DraftFile & caseid & ".rtf")

                        If fFile.Exists Then
                            'delete the file
                            fFile.Delete()
                        End If
                        If emailEvent > 0 Then
                            If tsk.DismissEvent(emailEvent, GlobalCRM.CurrentConID, "Email has been sent to the client", GlobalCRM.CurrentCaseID, 1) Then
                                emailEvent = 0
                            End If
                        End If
                        Me.Close()
                        Exit Sub
                    End If

                Else

                    If Letters.GblFunc_Send_MailEngine(Me.txtTo.Text.Trim, myCon.Email, Me.txtSubject.Text.Trim, txtbodyData.Text.Trim & vbCrLf & vbCrLf & Me.txtSignature.Text.Trim, Me.txtCC.Text.Trim, Me.txtBCC.Text.Trim, DocStoreId) = 0 Then
                        Me.btnSend.IsEnabled = True
                        CommonFuncs.DisplayMessage("Error. Message could not be added to the S_SendEmail table.", CommonDialog.CustomDialogIcons.Information, "Error")
                        Exit Sub
                    End If
                End If

                Dim Msg As New StringBuilder
                With Msg
                    .Append("Email Sent" & vbCrLf & vbCrLf & "To: " & Tostr)
                    If Me.txtCC.Text <> "" Then .Append(vbCrLf & vbCrLf & "CC: " & CC)
                    If Me.txtBCC.Text <> "" Then .Append(vbCrLf & vbCrLf & "BCC: " & Bcc)
                    If Me.chkBCCSender.IsChecked Then .Append(vbCrLf & vbCrLf & "BCC to Senders Inbox")
                    If Me.chkMailEngine.IsChecked Then .Append(vbCrLf & vbCrLf & "Sent via mail engine")
                    .Append(vbCrLf & "Subject: " & Subj)
                    If Me.lstAttach.Items.Count > 0 Then
                        .Append(vbCrLf & "Attachments: " & vbCrLf & "-----------------------")
                        For Each strAttachment As String In lstAttach.Items
                            .Append(vbCrLf & IO.Path.GetFileName(strAttachment))
                        Next
                        .Append(vbCrLf & "-----------------------")
                    End If
                   
                    .Append(vbCrLf & "Message: " & vbCrLf & vbCrLf & Msgstr)
                End With
                'code send mail through server
                Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
                Dim Smtp_Server As New SmtpClient
                Dim e_mail As New MailMessage()
                Smtp_Server.UseDefaultCredentials = False
                Dim userName As String = CType(configurationAppSettings.GetValue("emailserverusername", GetType(System.String)), String)
                Dim password As String = CType(configurationAppSettings.GetValue("emailserverpassword", GetType(System.String)), String)
                Dim test As Singleton = Singleton.Instance
                Smtp_Server.Credentials = New Net.NetworkCredential(test.CurrentConEmail, test.CurrentConEmailPassword)
                Smtp_Server.Port = 25
                'Smtp_Server.EnableSsl = True
                Dim smtpserver As String = CType(configurationAppSettings.GetValue("smtpserver", GetType(System.String)), String)
                Smtp_Server.Host = smtpserver

                e_mail = New MailMessage()
                e_mail.From = New MailAddress(EmailFrom)
                e_mail.To.Add(EmailTo)
                ' e_mail.Bcc = EMAILBCCSTRING
                e_mail.Subject = txtSubject.Text
                e_mail.IsBodyHtml = False
                Dim body As New StringBuilder
                body.AppendLine(txtbodyData.Text)
                body.AppendLine(txtSignature.Text)
                e_mail.Body = body.ToString()
                For Each attachment As GlobalCRM.LocalAttachments.LocalAttachment In GlobalCRM.LocalAttachments.Attachments
                    e_mail.Attachments.Add(New Net.Mail.Attachment(attachment.Filepath))
                Next
                Smtp_Server.Send(e_mail)
                If blnEmailToPerson = True Then
                    tsk.GblFunc_Add_Event("Send Email", Msg.ToString, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCandidateID, TasksEvents.EventTypes.EventPerson, , , , , 1)
                    blnEmailToPerson = False
                Else
                    tsk.GblFunc_Add_Event("Send Email", Msg.ToString, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , 1)
                End If
                If emailEvent > 0 Then
                    If tsk.DismissEvent(emailEvent, GlobalCRM.CurrentConID, "Email has been sent to the client", GlobalCRM.CurrentCaseID, 1) Then
                        emailEvent = 0
                    End If
                End If
                GlobalCRM.LocalAttachments.Attachments.Clear()


                caseid = CReg.ReadValue(GlobalCRM.GLOBALVISA, GlobalCRM.CUST, GlobalCRM.Reg_CurrentCASEID, value)
                strRegValue = CReg.ReadValue(GlobalCRM.GLOBALVISA, GlobalCRM.CUST, GlobalCRM.DRAFTSAVELOC, value)

                If strRegValue Is Nothing Then
                    strRegValue = CommonDataFunctions.getDraftForConsultant(GlobalCRM.CurrentConID)
                End If
                fFile = New IO.FileInfo(strRegValue & "\" & GlobalCRM.CurrentNTUserName & GlobalCRM.DraftFile & caseid & ".rtf")

                If fFile.Exists Then
                    'delete the file
                    fFile.Delete()
                End If
                Me.Close()
            End If
        Catch exc As Exception
            CommonFuncs.ErrorHandler(exc, "frmSendEmail.btnSend_Click")
        Finally
        End Try
    End Sub

    Private Sub btnRemoveAttach_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRemoveAttach.Click
        Dim i As Integer = Me.lstAttach.SelectedIndex
        If i <> -1 Then
            Me.lstAttach.Items.RemoveAt(i)
            GlobalCRM.LocalAttachments.Attachments.Remove(i + 1)
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
End Class
